<script setup lang="ts">
import { onMounted, ref } from "vue";
import { baseURL } from "@/service/http";

const token = window.localStorage.getItem('token')

const props = defineProps({
  direction: {
    type: Number,
  },
});


const imgUrl = ref("");
const imgUrlCopy = ref("");
const imgSize = ref(false);
onMounted(() => {
  token
});
const coverId= ref()
const handleUploadImg = (file: File) => {
  const blob = new Blob([file]);
  imgUrlCopy.value = URL.createObjectURL(blob);
};

// 成功回调
const handleUploadSuccess = (row: any) => {
  const { code,data, msg } = row;
  if (code === 200) {
    imgSize.value = true;
    imgUrl.value = imgUrlCopy.value;
    ElMessage.success("上传成功");
    coverId.value = data
  } else {
    ElMessage.warning(msg);
  }
};

// 文件上传失败时的钩子
const handleUploadError = () => {
  ElMessage.error("网络错误，请稍后再试");
};

defineExpose({
    coverId
})
</script>


<template>
  <el-upload
    :action="baseURL + '/oss/oss/update'"
    :headers="{ Authorization: token }"
    list-type="picture-card"
    :show-file-list="false"
    :before-upload="handleUploadImg"
    :on-success="handleUploadSuccess"
    :on-error="handleUploadError"
  >
    <div
      class="el-upload-bkg"
      ref="uploadBkg"
      :style="{ backgroundImage: `url(${imgUrl})` }"
      :class="{ 'el-upload-bkg-size': imgSize }"
    >
      <el-icon><Plus /></el-icon>
    </div>
  </el-upload>
</template>

<style scoped lang="less">
:deep(.el-upload--picture-card) {
  width: 200px;
  height: 200px;
}
.el-upload-bkg {
  width: 100%;
  height: 100%;
  text-align: center;
  line-height: 250px;
  background-repeat: no-repeat;
  background-position: center;
  i {
    font-size: 28px;
    color: var(--el-text-color-secondary);
  }
}
.el-upload-bkg-size {
  background-size: cover;
}
</style>